﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.Common;
using System.Data.SqlTypes;

namespace Alfred
{
	internal static class DBAL
	{
		static string ConnectionStrings { get; set; }
		static DbProviderFactory Factory { get; set; }
		static DbConnection StoreConnection { get; set; }
		static DbTransaction Transaction { get; set; }
		internal static SortedDictionary<string, string> Configuration { get; set; }

		static DBAL()
		{
			ConnectionStrings = "server=db372029455.db.1and1.com;User Id=dbo372029455;password=ghiltoniel;database=db372029455";

			Factory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
			Factory.CreateConnection();

			StoreConnection = GetConnection();
			StoreConnection.Open();
			Transaction = StoreConnection.BeginTransaction();
		}

		public static DbConnection GetConnection()
		{
			var conn = Factory.CreateConnection();
			conn.ConnectionString = ConnectionStrings;

			return conn;
		}

		static void AddParameter<T>(DbCommand cmd, string parameterName, T value)
		{
			var param = cmd.CreateParameter();
			param.ParameterName = parameterName;
			param.Value = value;

			cmd.Parameters.Add(param);
		}


		public static int GetHistoriqueId(string name)
		{
			using (var conn = GetConnection())
			{
				using (var query = conn.CreateCommand())
				{
					query.CommandText = "SELECT id FROM historique WHERE name=?name";

					AddParameter(query, "?name", name);
					conn.Open();
					var reader = query.ExecuteReader();
					reader.Read();
					return reader.GetInt32(0);
				}
			}
		}
	}
}